package ink.xiaobaibai.controller.buy;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import ink.xiaobaibai.annotation.InsidePublicResources;
import ink.xiaobaibai.autoConfig.roleResources.ResourcesRoleMapping;
import ink.xiaobaibai.common.MyRole;
import ink.xiaobaibai.common.RoleEvents;
import ink.xiaobaibai.common.SelectBuyBo;
import ink.xiaobaibai.entity.BuyOxygenDevice;
import ink.xiaobaibai.entity.BuyOzoneDevice;
import ink.xiaobaibai.response.ResponseFormat;
import ink.xiaobaibai.service.IAdminUserService;
import ink.xiaobaibai.service.IBuyOxygenDeviceService;
import ink.xiaobaibai.service.IBuyOzoneDeviceService;
import ink.xiaobaibai.units.MySecurity;
import ink.xiaobaibai.valited.UpdateGroup;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Set;

/**
 * @description: 氧气机控制层
 * @author: 小白白
 * @create: 2021-06-13
 **/

@RestController
@CrossOrigin
@RequestMapping("/buy/oxygen")
@Api(tags = "购买业务氧气机控制层")
@Slf4j
@InsidePublicResources
public class BuyOxygenDeviceController {

    @Autowired
    private IBuyOxygenDeviceService oxygenDeviceService;

    @Autowired
    private IBuyOzoneDeviceService ozoneDeviceService;

    @Autowired
    private IAdminUserService adminUserService;

    /**
     * 获取氧气机列表
     */
    @PostMapping("/list")
    @ApiOperation("获取氧气机列表")
    public ResponseFormat getOzoneList(@RequestBody @Validated SelectBuyBo selectBuyBo) {
        Integer userId = MySecurity.getUserId();
        Set<String> roles = MySecurity.getRoles();
        if (!roles.contains(MyRole.POWER_BUY)) {
            RoleEvents roleEvents = new RoleEvents(MySecurity.getRole());
            roleEvents
                    .agent(() -> selectBuyBo.setDepId(this.adminUserService.getDepId(userId)))
                    .distributor(() -> selectBuyBo.setAdminUserId(userId))
                    .admin(() -> {
                    })
                    .execute();
        }
        return ResponseFormat.success(this.oxygenDeviceService.getList(selectBuyBo));
    }

    /**
     * 增加氧气机
     */
    @PostMapping("/add")
    @ApiOperation("增加氧气机")
    @ResourcesRoleMapping(resourceName = "增加购买氧气机器", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_BUY})
    public ResponseFormat addOxygenDevice(@RequestBody @Validated BuyOxygenDevice buyOxygenDevice) {
        Integer userId = MySecurity.getUserId();
        Integer depId;
        if (buyOxygenDevice.getAdminUserId() == null) {
            depId = this.adminUserService.getDepId(userId);
        } else {
            if (!this.adminUserService.existsUser(buyOxygenDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            userId = buyOxygenDevice.getAdminUserId();
            depId = this.adminUserService.getDepId(buyOxygenDevice.getAdminUserId());
        }
        buyOxygenDevice.setAdminUserId(userId);
        buyOxygenDevice.setDepId(depId);
        if (!this.oxygenDeviceService.okCode(buyOxygenDevice.getDeviceCode())) {
            return ResponseFormat.fail("机器码重复");
        }
        this.oxygenDeviceService.save(buyOxygenDevice);
        return ResponseFormat.success();
    }

    /**
     * 删除氧气机
     */
    @DeleteMapping("/delete/lower/{id}")
    @ApiOperation("删除氧气机")
    @ResourcesRoleMapping(resourceName = "删除购买氧气机器", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_BUY})
    public ResponseFormat deleteOxygenDeviceLower(@PathVariable("id") Integer deviceId) {
        if (!MySecurity.isPower(MyRole.POWER_BUY)) {
            return ResponseFormat.fail("权限不足");
        }
        QueryWrapper<BuyOzoneDevice> q1 = new QueryWrapper<>();
        q1.eq("oxygen_id", deviceId);
        q1.last("limit 1");
        if (this.ozoneDeviceService.count(q1) > 0) {
            return ResponseFormat.fail("当前氧气机与对应臭氧机绑定中");
        }
        QueryWrapper<BuyOxygenDevice> q2 = new QueryWrapper<>();
        q2.select("admin_user_id", "client_user_id");
        q2.eq("id", deviceId);
        BuyOxygenDevice oxygenDevice = this.oxygenDeviceService.getOne(q2);
        if (oxygenDevice.getClientUserId() != null) {
            return ResponseFormat.fail("当前机器已绑定客户");
        }
        this.oxygenDeviceService.removeById(deviceId);
        return ResponseFormat.success();
    }

    /**
     * 修改氧气机
     */
    @PutMapping("/update")
    @ApiOperation("修改氧气机")
    @ResourcesRoleMapping(resourceName = "修改购买氧气机器", includeRoleNames = {MyRole.ADMIN, MyRole.POWER_BUY})
    public ResponseFormat updateOxygen(@RequestBody @Validated(value = UpdateGroup.class) BuyOxygenDevice buyOxygenDevice) {
        Integer userId = MySecurity.getUserId();
        QueryWrapper<BuyOxygenDevice> q1 = new QueryWrapper<>();
        q1.select("admin_user_id", "device_code");
        q1.eq("id", buyOxygenDevice.getId());
        BuyOxygenDevice oxygenDevice = this.oxygenDeviceService.getOne(q1);
        if (buyOxygenDevice.getAdminUserId() != null && !StringUtils.equals(String.valueOf(buyOxygenDevice.getAdminUserId()), String.valueOf(oxygenDevice.getAdminUserId()))) {
            if (!this.adminUserService.existsUser(buyOxygenDevice.getAdminUserId())) {
                return ResponseFormat.fail("绑定用户不存在");
            }
            buyOxygenDevice.setDepId(this.adminUserService.getDepId(buyOxygenDevice.getAdminUserId()));
        }
        if (!oxygenDevice.getDeviceCode().equals(buyOxygenDevice.getDeviceCode())) {
            if (!this.oxygenDeviceService.okCode(buyOxygenDevice.getDeviceCode())) {
                return ResponseFormat.fail("机器码重复");
            }
        }
        if (oxygenDevice.getClientUserId() != null && buyOxygenDevice.getClientUserId() != null && !oxygenDevice.getClientUserId().equals(buyOxygenDevice.getClientUserId())) {
            log.error("敏感操作:{}将机器{}的客户id改为{},原{}", userId, buyOxygenDevice.getId(), buyOxygenDevice.getClientUserId(), oxygenDevice.getClientUserId());
        }
        this.oxygenDeviceService.updateById(buyOxygenDevice);
        return ResponseFormat.success();
    }

}
